<template>
  <div class="time">
    <el-timeline style="width: 100%;">
      <el-scrollbar>
      <el-timeline-item v-for="(activity, index) in activities" :key="index">
        <template #default>
          <el-card style="width: 100%;">
            <!-- 头像 -->

            <div class="time-content">
              <div style="display: flex;align-items: center;margin-bottom: 10px;">
                <img style="width: 30px;height: 30px;border-radius: 50%;margin-right: 10px;" :src="activity.avatar"
                  alt=""><span>{{
                    activity.userName }}</span>
                <SvgIcon style="cursor: pointer;" class="edit" name="编辑" :size="22" @click = "openEditDialog(activity)"/>
              </div>
<!--              <p>{{ activity.content }}</p>-->

              <p v-if="!activity.isContentEditable" @click="activity.isContentEditable = true">{{ activity.content }}</p>
              <el-input v-else v-model="activity.content" @blur="updRecord(activity)" @keyup.enter="updRecord(activity)"/>
              <div v-if="aiStreamLine" class="flex" style="justify-content: start;margin-top: 20px">
                <SvgIcon    name="精简" :size="15"  />
<!--                <p style="color: #4861FF;">{{ activity.aiStreamline }}</p>-->
                <p v-if="!activity.isEditable" @click="activity.isEditable = true">{{ activity.aiStreamline }}</p>
                <el-input v-else v-model="activity.aiStreamline" @blur="updRecord(activity)" @keyup.enter="updRecord(activity)"/>
              </div>
              <audio :src="activity.mediaUrl" controls>
                Your browser does not support the audio element.
              </audio>
            </div>

          </el-card>
        </template>
        <template #dot>
          <SvgIcon name="单选框" />
          <span class="time-dot-time">{{ activity.timestamp }}</span>
        </template>
      </el-timeline-item>
      </el-scrollbar>
    </el-timeline>
    <el-dialog align-center v-model="editDialog" width="450" :before-close="handleClose">
      <p style="width: 100%;text-align: center;font-size: 18px;margin-bottom: 20px;">人员信息</p>
      <div style="display: flex;justify-content: center;flex-direction: column;align-items: center;">
        <img :src="editForm.profilePicUrl" alt="" style="width: 68px;height: 68px;border-radius: 50%;margin-bottom: 10px;box-shadow: 0 0 0 2px #4861FF;padding: 5px;">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleUpload"
        >
          <el-button type="primary" round plain style="margin-bottom: 20px;">更改头像</el-button>
        </el-upload>

      </div>
      <el-form label-position="top" :rules="rules" :model="editForm" label-width="auto"
               style="width: 100%;padding: 0 40px;" ref="formRef">
        <el-form-item label="姓名"  prop="name">
          <el-input v-model="editForm.name" clearable />
        </el-form-item>
        <el-form-item label="邮箱" class="input-item" prop="emailAddr">
          <el-input v-model="editForm.emailAddr" clearable />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="editForm.editFlag" label="修改本次会议记录中全部此发言人的信息" size="large" />

        </el-form-item>
        <el-form-item>
          <div style="width: 100%; display: flex;justify-content: space-between;margin-top: 30px;">
            <el-button size="large" style="width: 40%;" round @click ="editDialog = false">取消</el-button>
            <el-button size="large" style="width: 40%; " type="primary" round @click="handleSubmit">确定</el-button>

          </div>

        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import SvgIcon from '@/components/SvgIcon.vue'
import {onMounted,watch,ref } from 'vue'
import {getMeetingRecordById, getUserById, updateRecord, updateUserById, upload} from "@/api/index.js";
import {ElMessage} from "element-plus";

const activities = ref([])

const editDialog = ref(false)
const props = defineProps({
  meetingId: {
    type: String,
    default: () => { }
  },
  aiStreamLine: {
    type: Boolean,
    default: () => { }
  }
}
)

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('文件格式不正确!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('超出图片大小!')
    return false
  }
  return true
}
const handleUpload = async (e) => {
  const formData = new FormData();
  const reader = new FileReader();
  reader.readAsArrayBuffer(e.file); // 读取文件为 ArrayBuffer
  reader.onload = async (loadEvent) => {
    const arrayBuffer = loadEvent.target.result;
    let file = new File([arrayBuffer],  e.file.name);
    formData.append('file', file);
    const data = await upload(formData)
    if(data.code === 200) {
      editForm.value.profilePicUrl = data.data.url
      ElMessage.success("上传成功")
    }
  }
}



const validateUsername = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入姓名'));
  } else {
    callback();
  }
};

const validateEmail = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请正确填写邮箱'));
  } else {
    if (value !== '') {
      var reg=/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if(!reg.test(value)){
        callback(new Error('邮箱格式错误'));
      }
    }
    callback();
  }
};

const editForm = ref({
  recordId:'',
  profilePicUrl: '',
  name: '',
  emailAddr: '',
  id:'',
  editFlag:ref(true)
})
const rules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur',validator: validateUsername },
  ],
  emailAddr: [
    { required: true, trigger: 'blur',validator: validateEmail  },
  ],
})
const formRef = ref(null);

const handleClose = () => {
  editDialog.value = false
  editForm.value = {}
}
const openEditDialog = async(item) =>{
  let formData = new FormData();
  formData.append("userId",item.userId)
  const userData = await getUserById(formData);
  editForm.value = {
    recordId:item.id,
    profilePicUrl: userData.data.profilePicUrl,
    name: userData.data.name,
    emailAddr: userData.data.emailAddr,
    id:userData.data.id,
    editFlag:editForm.value.editFlag
  }
  editDialog.value = true
}

const cancelDialog = () =>{
  editForm.value = {}
  editDialog.value = false
}

const updRecord = async (item) =>{
  let formData = new FormData();
  formData.append("recordId", item.id)
  formData.append("content", item.content)
  formData.append("aiStreamline", item.aiStreamline)
  const data = await updateRecord(formData)
  item.isEditable = false
  item.isContentEditable = false
}

const handleSubmit = async () =>{
  console.log(editForm.value.editFlag)
  formRef.value.validate(async (valid) => {
    if (valid) {
      const data = await updateUserById(editForm.value);
      if(data.code === 200){
        ElMessage.success("修改成功")
        activities.value = []
        const formData = new FormData();
        formData.append("meetingId",props.meetingId);
        getMeetingRecordById(formData).then(res => {
          if(res.code === 200){
            res.data.forEach(item => {
              activities.value.push({
                id:item.id,
                content: item.record,
                userId:item.userId,
                timestamp: item.speakTime,
                userName: item.userName,
                avatar: item.profilePicUrl,
                mediaUrl: item.voiceUrl,
                aiStreamline:item.aiStreamline
              })
            })
          }
        })
      }else{
        ElMessage.error("修改失败")
      }
      editDialog.value = false
      // 处理提交逻辑
    } else {
      return false;
    }
  });
}


watch(() => props.meetingId,async () => {
  activities.value = []
  const formData = new FormData();
  formData.append("meetingId",props.meetingId);
  getMeetingRecordById(formData).then(res => {
    if(res.code === 200){
      res.data.forEach(item => {
        activities.value.push({
          id:item.id,
          content: item.record,
          userId:item.userId,
          timestamp: item.speakTime,
          userName: item.userName,
          avatar: "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
          mediaUrl: item.voiceUrl,
          aiStreamline:item.aiStreamline
        })
      })
    }

  })
})

</script>

<style lang="scss" scoped>
.time {
  display: flex;
  width: 100%;
  height: 100%;
  padding: 0 150px;
  overflow-y: auto;

  :deep(.el-timeline-item__dot) {
    position: absolute;

    .time-dot-time {
      position: absolute;
      width: 100px;
      left: -100px;
    }
  }

  .time-content {
    audio {

      width: 100%;
      height: 40px;
      opacity: .8;
      margin-top: 10px;
    }
    .edit:hover {
      color: #1890ff; /* 鼠标悬停时的文本颜色 */
      text-decoration: underline; /* 鼠标悬停时添加下划线 */
    }
  }
}
</style>
